package org.inspiration.dudu.common.util;

import cn.hutool.core.util.StrUtil;
import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTUtil;

import org.inspiration.dudu.common.constant.Constant;
import org.inspiration.dudu.common.exception.ServiceException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

@Component
public class JwtUtil {

    @Value("${dudu.jwt.key}")
    private String key;

    public String getToken(Long id, String username) {
        Map<String, Object> map = new HashMap<String, Object>() {
            private static final long serialVersionUID = 1L;

            {
                put("id", id);
                put("username", username);

            }
        };
        return JWTUtil.createToken(map, key.getBytes());
    }

    public boolean verifyToken(String token) {
        if (StrUtil.isBlank(token)) {
            return false;
        }
        return JWTUtil.verify(token, key.getBytes());
    }

    public Long getIdByToken(String token) {
        if (!verifyToken(token)) {
            throw new ServiceException(Constant.JWT_INVALID);
        }
        // 解析 JWT Token
        JWT jwt = JWTUtil.parseToken(token);

        // 获取 payload 中的 "id" 字段
        String userId = jwt.getPayload("id").toString();

        return Long.parseLong(userId);
    }

    public String getUsernameByToken(String token) {
        if (!verifyToken(token)) {
            throw new ServiceException(Constant.JWT_INVALID);
        }
        // 解析 JWT Token
        JWT jwt = JWTUtil.parseToken(token);

        // 获取 payload 中的 "id" 字段

        return jwt.getPayload("username").toString();

    }
}